package com.jieao.front.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.jieao.common.constant.Constants;
import com.jieao.common.constant.SmsConstants;
import com.jieao.common.constant.UserConstants;
import com.jieao.common.core.controller.BaseController;
import com.jieao.common.core.domain.AjaxResult;
import com.jieao.common.utils.CacheUtils;
import com.jieao.common.utils.RandomUtil;
import com.jieao.common.utils.StringUtils;
import com.jieao.content.dto.ArticleDto;
import com.jieao.framework.shiro.service.SysRegisterService;
import com.jieao.framework.util.ShiroUtils;
import com.jieao.generator.dto.SmsSendDto;
import com.jieao.generator.service.ISmsService;
import com.jieao.system.domain.SysDictData;
import com.jieao.system.domain.SysUser;
import com.jieao.system.service.ISysUserService;
import com.jieao.system.utils.DictUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 前端 控制器
 * @Author weifanl
 * @Date2020/7/12 13:14
 **/
@Controller
@RequestMapping("/front")
public class FrontController extends BaseController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private SysRegisterService registerService;

    /**
     * 登录页面
     *
     * @Author LWF
     * @Date 23:41 2020/7/12
     **/
    @GetMapping(value = "/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        return "front/login";
    }

    /**
     * 登录
     *
     * @Author LWF
     * @Date 23:33 2020/7/14
     **/
    @PostMapping("/login")
    public String doLogin(@RequestParam Map<String, String> params, ModelMap mmap) {
        SysUser sysUser = sysUserService.selectUserByPhoneNumber(params.get("phonenumber"));
        if (null == sysUser) {
            mmap.put("msg", "用户未注册");
            return "front/login";
        }
        Boolean rememberMe = true;
        if (StringUtils.isEmpty(params.get("rememberMe"))) {
            rememberMe = false;
        }
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getLoginName(), params.get("password"), rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            mmap.put("user", sysUser);
            return "front/index";
        } catch (AuthenticationException e) {
            logger.info(e.getMessage());
            mmap.put("msg", "密码错误");
            return "front/login";
        }
    }

    /**
     * 注册页面
     *
     * @Author LWF
     * @Date 23:41 2020/7/12
     **/
    @GetMapping(value = "/register")
    public String register(HttpServletRequest request, HttpServletResponse response) {
        return "front/register";
    }

    /**
     * 注册
     *
     * @Author LWF
     * @Date 23:41 2020/7/12
     **/
    @PostMapping(value = "/register")
    @ResponseBody
    public AjaxResult doRegister(@RequestParam Map<String, String> params) {
        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(params.get("phonenumber"));
        sysUser.setVerifyCode(params.get("verifyCode"));
        sysUser.setUserName(params.get("userName"));
        sysUser.setLoginName(params.get("userName"));
        sysUser.setPassword(params.get("password"));
        sysUser.setSex(params.get("sex"));
        sysUser.setUserType(UserConstants.FRONT_USER_TYPE);
        //验证短信验证码
        SysDictData dictCache = DictUtils.getDictCache("sys_sms", SmsConstants.REGISTER);

        Long time = (Long) CacheUtils.get(Constants.BIZ_CACHE, "sms:" + dictCache.getDictValue() + ":" + sysUser.getPhonenumber() + "time");
        String code = (String) CacheUtils.get(Constants.BIZ_CACHE, "sms:" + dictCache.getDictValue() + ":" + sysUser.getPhonenumber());
        if (StringUtils.isEmpty(code) || null == time) {
            return AjaxResult.success("未发送验证码");
        }

        if (time != null && System.currentTimeMillis() - time < 60 * 1000 * 5 && sysUser.getVerifyCode().equals(code)) {
            sysUser.setUserType(UserConstants.REGISTER_USER_TYPE);
            return AjaxResult.success(registerService.register(sysUser));
        } else {
            return AjaxResult.success("验证码错误");
        }
    }


    /**
     * 发送验证码
     *
     * @Author LWF
     * @Date 23:41 2020/7/12
     **/
    @PostMapping(value = "/getCode")
    @ResponseBody
    public AjaxResult getCode(@RequestParam("phonenumber") String phone, @RequestParam("sign") String sign) {
        SysDictData dictCache = DictUtils.getDictCache("sys_sms", sign);

        Long time = (Long) CacheUtils.get(Constants.BIZ_CACHE, "sms:" + dictCache.getDictValue() + ":" + phone + "time");

        if (time != null && System.currentTimeMillis() - time < 60 * 1000) {
            return AjaxResult.warn("每60秒只能发送一次");
        }

        SmsSendDto dto = new SmsSendDto();
        dto.setModuleId(dictCache.getDictValue());
        dto.setPhone(phone);
        //验证码
        Integer code = RandomUtil.getRandomForIntegerBounded4(1000, 9999);
        Map<String, String> map = new HashMap<>();
        map.put("code", code.toString());
        dto.setParams(map);

        smsService.send(dto);
        CacheUtils.put(Constants.BIZ_CACHE, "sms:" + dictCache.getDictValue() + ":" + phone + "time", System.currentTimeMillis());
        CacheUtils.put(Constants.BIZ_CACHE, "sms:" + dictCache.getDictValue() + ":" + phone, code.toString());

        return AjaxResult.success("发送成功");
    }


}
